<template>
  <div id="writediary" >
    <el-dialog style="background-color: #a0cba0"title="植物养成日记" :visible.sync="visible" top="0.5rem" :lock-scroll="false" :show-close="false" :close-on-click-modal="false">
      <el-form ref="DiaryForm" :model="plantDiary" label-width="100px">
        <el-form-item label="植物名字:" prop="plantName" >
          <div style="display:grid;justify-content:start">{{plant.plantName}}</div>
        </el-form-item>
        <el-form-item label="植物种类:">
          <div style="display:grid;justify-content:start">{{plantCategory}}</div>
        </el-form-item>
        <el-form-item label="植物状态:" prop="state" >
          <div style="display:grid;justify-content:start">{{plantDiary.state}}</div>
        </el-form-item>
        <el-form-item label="日期:" prop="createTime" >
          <div style="display:grid;justify-content:start">{{plantDiary.createTime}}</div>
        </el-form-item>
        <el-form-item label="天气:" prop="weather" >
          <el-select v-model="plantDiary.weather" placeholder="天气" style="width: 100px;right: 200px">
            <el-option
                v-for="item in weatherList"
                :key="item"
                :label="item"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日记标题：" prop="summary">
          <el-input v-model="plantDiary.title" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="日记内容：" prop="description">
          <el-input type="textarea" :rows="10" v-model="plantDiary.content" resize="none" maxlength="500" show-word-limit palceholder="备注"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="avatarlist" style="display:grid;justify-content:start">
            <el-upload

                name="img"
                :action="uploadURL"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
              <img   v-if="plantDiary.picture" :src="plantDiary.picture" width="300" height="200">
              <i v-else class="el-icon-plus avatar-uploader-icon"  width="300" height="200"></i>
              <div style="margin-top: 50px" slot="tip" class="el-upload__tip">点击上传图片，只能上传jpg/png文件，且不超过1mb</div>
            </el-upload>
          </div>
        </el-form-item>

      </el-form>
      <span slot="footer">
      <el-button type="info" @click="resetForm('plantForm')">取消</el-button>
      <el-button v-if="edit_add===0" type="primary" @click="ifSaveDiary(plantDiary)">保存</el-button>
        <el-button v-if="edit_add===1" type="warning" @click="ifSaveDiary(plantDiary)">保存</el-button>
        <el-button v-if="edit_add===0" type="success" @click="submitToCommunity(plantDiary)">保存并发布到社区</el-button>
         <el-button v-if="edit_add===1" type="success" @click="submitToCommunity(plantDiary)">发布到社区</el-button>

    </span>
    </el-dialog>
  </div>
</template>

<script>
import store from "@/store";
import {getPlantCategoryById} from "@/api/plantCategory";
import {addDiary} from "@/api/diary";
import {getMyPlant} from "@/api/plant";
import {addArticle} from "@/api/article";

export default {
  name: "WriteDiary",
  data(){
    return{
      plant:{
        plantId:'',
        plantName:'',
        categoryId:'',
        avatar:'',
        status:'',
        description:'',
        followerNum:'',
        plantAge:'',
        createBy:'',
        createTime:'',
        updateBy:'',
        updateTime:''
      },
      plantDiary:{
        id:'',
        plantId:'',
        weather:'',
        state:'',
        content:'',
        picture:'',
        isComment:'',
        likeCount:'',
        createBy:'',
        createTime:'',
        updateBy:'',
        updateTime:'',
        title:'',

      },
      plantArticle:{
        id:'',
        //标题
        title:'',
        //文章内容
        content:'',
        //文章摘要
        summary:'',
        //所属分类id：属于哪个专区
        categoryId:'',
        //缩略图
        thumbnail:'',
        //是否置顶（0否，1是）
        isTop:'',
        //状态（0已发布，1草稿）
        status:'',
        //访问量
        viewCount:'',
        //是否允许评论 是，1否
        isComment:'',

        createBy:'',

        createTime:'',

        updateBy:'',

        updateTime:'',
        //删除标志（0代表未删除，1代表已删除）
        delFlag:'',
        //文章类型（0每日百科，1分享，2求助，3解答  4:商家发帖 5:日记）
        typeId:5,
        //点赞量
        likeCount:'',
        //收藏量
        collectCount:'',
        //关联植物id
        plantId:''
      },
      plantCategory:'',
      date:'',
      weather:'',
      picture:'',
      isComment:'',
      likeCount:'',
      uploadURL:'',
      weatherList:['晴','雨','阴','风','雪'],
      visible:false,
      edit_add:0
      
    }
  },
  mounted() {

  },
  created() {
    this.uploadURL = store.state.baseURL+'upload'
    console.log(this.uploadURL)
  },

  methods:{
    routeChange(){

    },
    format() {
      const nowDate = new Date();
      const date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate(),
      }
      const newmonth = date.month > 9 ? date.month : '0' + date.month
      const day = date.date > 9 ? date.date : '0' + date.date
      this.date = date.year + '.' + newmonth + '.' + day

    },
    open(item,diary,add_or_edit){

      console.log("diarysssss")
      this.visible=true

      if(add_or_edit===0){
        this.edit_add=0
        this.plant.plantId=item.plantId
        this.plant.plantName=item.plantName
        this.plant.status=item.status
        this.plant.avatar=item.avatar
        this.plant.categoryId=item.categoryId
        this.plant.description=item.description
        this.plant.followerNum=item.followerNum
        this.plant.createBy=item.createBy
        this.plant.updateBy=item.updateBy
        this.plant.updateTime=item.updateTime
        this.plantDiary.plantId=item.plantId
        this.plantDiary.state=item.status
        this.plantDiary.createBy=item.createBy
        this.format()
        this.plantDiary.createTime=this.date
        this.getPlantCategoryStr(this.plant.categoryId)
      }else if(add_or_edit===1){
        this.edit_add=1
        this.plantDiary.plantId=diary.plantId
        this.plantDiary.picture=diary.picture
        this.plantDiary.state=diary.state
        this.plantDiary.createTime=diary.createTime
        this.plantDiary.content=diary.content
        //this.plantDiary.createTime=diary.createTime
        this.plantDiary.createBy=diary.createBy
        this.plantDiary.isComment=diary.isComment
        this.plantDiary.weather=diary.weather
        this.plantDiary.title=diary.title
        this.plantDiary.id=diary.id
        this.plantDiary.likeCount=diary.likeCount
        this.plantDiary.updateBy=diary.createBy
        this.format()
        this.plantDiary.updateTime=this.date
        this.getPlant(diary.plantId)
        //this.getPlantCategoryStr(this.plant.categoryId)
      }


    },
    getPlant(id){
      getMyPlant(id).then(res=>{
        this.plant=(JSON.parse(JSON.stringify(res)).records)[0]
        console.log("plant:111",this.plant)
        this.getPlantCategoryStr(this.plant.categoryId)
      })
    },
    getPlantCategoryStr(id){
      console.log("plantid11312:",id)
      getPlantCategoryById(id).then(res =>{
        console.log(res.plantCategoryName)
        this.plantCategory=res.plantCategoryName
      })

    },
    handleAvatarSuccess(res, file) {//上传头像
      console.log("plant_img",res)
      if(res != null){
        this.plantDiary.picture = res;
      }else{
        this.$message.error('上传图片失败');
      }

    },
    beforeAvatarUpload(file) {//判断图片大小
      const isJPG = file.type == 'image/png'||file.type=='image/jpg'||file.type=='image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/JPEG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return isJPG && isLt2M;
    },
    saveDiary(plantDiary){
      if(this.edit_add===0){
        addDiary(plantDiary).then(res=>{
          console.log(plantDiary)
        })
      }else if(this.edit_add===1){
        // updateDiary(plantDiary).then(()=>{
        //   console.log(plantDiary)
        // })
        console.log('this.fileList', this.fileList)
        this.$emit('confirmData', this.plantDiary,this.fileList)
        this.resetForm('DiaryForm')
      }

    },
    saveAsArticle(diary){
      this.plantArticle.title=diary.title
      this.plantArticle.content=diary.content
      this.plantArticle.thumbnail=diary.picture
      this.plantArticle.plantId=diary.plantId
      this.plantArticle.createBy=diary.createBy
      this.plantArticle.createTime=this.date
      this.plantArticle.summary=diary.content
      this.plantArticle.categoryId=this.plant.categoryId
      console.log(this.plantArticle)
      addArticle(this.plantArticle).then(res=>{

      })

    },
    submitToCommunity(plantdiary1){
      this.$confirm('确认发布吗？', '是否发布', {
        cancelButtonText: '取消',
        confirmButtonText: '确认',
        lockScroll: false,
        type: 'warning'
      }).then(() => {
        this.saveAsArticle(plantdiary1)
        if(this.edit_add===0){
          this.saveDiary(plantdiary1)
        }
        this.$message.success("发布日记成功")
        this.resetForm()
      })
    },
    ifSaveDiary (plantDiary) {
          this.$confirm('确认保存吗？', '是否保存', {
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            lockScroll: false,
            type: 'warning'
          }).then(() => {
            this.saveDiary(plantDiary)
            this.$message.success("保存日记成功")
            this.resetForm()
          })

    },
    resetForm (plantForm) {
      this.$nextTick(() => {
        this.$refs.DiaryForm.clearValidate()
      })
      this.plant = {}
      this.plantDiary={}
      this.plantArticle={}
      this.visible = false
    }
  }
}
</script>

<style scoped>

</style>